package com.tan00xu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tan00xu.dao.ArticleMapper;
import com.tan00xu.dao.CommentMapper;
import com.tan00xu.pojo.Article;
import com.tan00xu.pojo.Comment;
import com.tan00xu.pojo.User;
import com.tan00xu.service.CommentService;
import com.tan00xu.service.UserService;
import com.tan00xu.utils.CmdOutputInformationUtils;
import com.tan00xu.utils.UserThreadLocal;
import com.tan00xu.vo.CommentVo;
import com.tan00xu.vo.UserVo;
import com.tan00xu.vo.Result;
import com.tan00xu.vo.params.CommentParam;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {


    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleMapper articleMapper;


    /**
     * 根据文章id获取评论
     * @param articleId 文章id
     * @return Result 评论
     */
    @Override
    public Result getCommentsByArticleId(Long articleId) {
        /*
            1. 根据文章id查询评论列表
            2. 根据评论者id查询评论者信息
            3. 判断 如果 level 为 1 则查询该评论有无子级评论
            4. 如果有子级评论则根据(parentId)查询子级评论
         */
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArticleId,articleId);
        queryWrapper.eq(Comment ::getLevel,1);
        queryWrapper.orderByDesc(Comment::getCreateDate);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        List<CommentVo> commentVoList = copyList(comments);
        CmdOutputInformationUtils.info("文章评论，文章："+articleId+"的评论为：\n"+commentVoList);
        return Result.success("评论加载成功",commentVoList);
    }

    /**
     * 发表评论
     * @param commentParam 评论所需参数
     * @return Result
     */
    @Override
    public Result createComment(CommentParam commentParam) {
        User user = UserThreadLocal.get();
        Comment comment = new Comment();
        comment.setArticleId(commentParam.getArticleId());
        comment.setCriticId(user.getId());
        comment.setContent(commentParam.getContent());
        comment.setCreateDate(System.currentTimeMillis());
        Long parentId = commentParam.getParentId();
        if (parentId == null || parentId == 0) {
            comment.setLevel(1);
        }else{
            comment.setLevel(2);
        }
        comment.setParentId(parentId == null ? 0 : parentId);
        Long toCriticId = commentParam.getToCriticId();
        comment.setToCriticId(toCriticId == null ? 0 : toCriticId);
        this.commentMapper.insert(comment);

        //更新评论数
        UpdateWrapper<Article> updateWrapper = Wrappers.update();
        updateWrapper.eq("id",comment.getArticleId());
        updateWrapper.setSql(true,"comment_counts=comment_counts+1");
        this.articleMapper.update(null,updateWrapper);

//        Result commentsByArticleId = getCommentsByArticleId(commentParam.getArticleId());
        CommentVo commentVo = copy(comment);
        return Result.success("发表评论成功",commentVo);
    }


    /**
     * 根据父级评论id查询到子级评论
     * @param parentId 父级评论id
     * @return List<CommentVo> 子级评论列表
     */
    private List<CommentVo> getCommentByParentId(Long parentId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId,parentId);
        queryWrapper.gt(true,Comment ::getLevel,1);
        return copyList(commentMapper.selectList(queryWrapper));
    }


    private List<CommentVo> copyList(List<Comment> comments) {
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : comments) {
            commentVoList.add(copy(comment));
        }
        return commentVoList;
    }

    private CommentVo copy(Comment comment) {
        CommentVo commentVo = new CommentVo();
        BeanUtils.copyProperties(comment,commentVo);
        //时间格式化
        commentVo.setCreateDate(new DateTime(comment.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //评论者的id
        Long criticId = comment.getCriticId();
        //评论者的信息
        UserVo critic = this.userService.getUserVoByUserId(criticId);
        commentVo.setCritic(critic);
        //子级评论
        List<CommentVo> commentVoChildren = getCommentByParentId(comment.getId());
        commentVo.setChildren(commentVoChildren);

        if (comment.getLevel() > 1) {
            //被评论的人的id
            Long toUid = comment.getToCriticId();
            //被评论的人的信息
            UserVo userVo = this.userService.getUserVoByUserId(toUid);
            commentVo.setToCritic(userVo);
        }
        return commentVo;
    }


}
